<template>
  <div class="main">
    <el-button type="primary" @click="login">登录聊天室</el-button>
    <el-button type="primary" @click="layout">退出</el-button>

    <div class="box">
      <el-row :gutter="10" style="height: 100%">
        <el-col :span="6" style="height: 100%">
          <div class="list">
            <div class="headList">
              当前用户<span style="margin-left: 4px; font-weight: 700">({{ user.loginName }})</span>
            </div>
            <el-menu background-color="#CCC" :default-active="activeIndex" @open="handleOpen" @select="handleSelect">
              <el-menu-item v-for="(item, index) in userList" :key="index" :index="item.key">
                <p :class="`${item.isOnline ? 'text_color' : 'text_color_is'}`">
                  {{ item.label }}
                  <span style="font-size: 12px; color: #ae9595" v-if="!item.isOnline">(不在线)</span>
                </p>
              </el-menu-item>
            </el-menu>
          </div>
        </el-col>
        <el-col :span="18">
          <div v-if="noUserState">
            <div class="title">{{ title }}</div>
            <div style="height: 100%">
              <div class="talk">
                <div class="main_body">
                  <div :class="`${i.myName === roomName ? 'my' : 'other_user'}`" v-for="(i, index) in MessageList"
                    :key="index">
                    <div :class="`${i.myName === roomName ? 'my_head_img' : 'head_img'}`"></div>
                    <div :class="`${i.myName === roomName ? 'my_content' : 'content'}`">
                      {{ i.content }}
                    </div>
                  </div>
                </div>
              </div>
              <div class="sendMsg">
                <textarea v-model="message" rows="4" />
                <el-button size="small" @keyup.enter="enterdown" @click="sendMsg">发送</el-button>
              </div>
            </div>
          </div>
          <div v-else>
            <el-empty description="暂无信息" />
          </div>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import myWebSocket from "@/utils/ws";
import { ref, onMounted, onUnmounted, watch } from "vue";
import { ElMessage } from "element-plus";
import { adminStorage } from "@/utils/storage";
import { userList_Api } from "@/api/sys/user";
let message = ref("");
let noUserState = ref(true);
let userList = ref([]);
let title = ref("");
let MessageList = ref([]);
let user = adminStorage.getSession("userInfo");
let roomName = ref(user.id + "$" + user.loginName); //当前用户
const activeIndex = ref("");

onMounted(() => {
  window.addEventListener("keydown", enterdown);
});
const roomocket = new myWebSocket({
  otp: {
    message: false,
    keyValue: "getRoomUser",
  },
});

// 获取所有用户列表
const getAdminUsers = async () => {
  try {
    let { data } = await userList_Api({
      count: 9999,
      page: 1,
    });
    let list = data.records.map((e) => {
      return {
        key: e.user_id + "$" + e.loginName,
        label: e.loginName,
        isOnline: false,
      };
    });
    return (userList.value = [...list]);
  } catch (e) {
    console.error(e);
  }
};
onUnmounted(() => {
  // 销毁断开连接
  roomocket.closeFn();
  window.removeEventListener("keydown", enterdown, false);
});

roomocket.createFn("/room", "/socketIo", { user: roomName.value });
watch(
  activeIndex,
  (newValue) => {
    noUserState.value = newValue == "" ? false : true;
  },
  { immediate: true }
);

watch(
  roomocket.messageArr,
  (newValue) => {
    if (newValue && newValue.length > 0) {
      getUserList(newValue);
    }
  },
  { immediate: true, deep: true }
);
const getUserList = (list) => {
  // 获取在线人员
  userList.value.forEach((e) => {
    e.isOnline = false;
    for (let i = 0; i < list.length; i++) {
      if (e.key === list[i]) {
        e.isOnline = true;
      }
    }
  });
};

// 登录
const login = async () => {
  let res = await getAdminUsers();
  if (res) {
    roomocket.createFn("/room", "/socketIo", { user: roomName.value }, (socket) => {
      console.log(roomocket.messageArr, "roomocket");
      setTimeout(() => {
        getUserList(roomocket.messageArr.value);
      });
      ElMessage({
        message: "登录成功",
        type: "success",
      });
    });
  }
};
// 退出
const layout = () => {
  activeIndex.value = "";
  noUserState.value = false;
  roomocket.closeFn();
  userList.value.length = 0;
  MessageList.value.length = 0;
};
// 选中某个用户
const handleSelect = (key) => {
  activeIndex.value = key;
  if (userList.value.length > 0)
    title.value = userList.value.find((e) => e.key === key).label;
  // 当前用户和发送用户合成唯一主键
  let data = {};
  data.recordsID = activeIndex.value + "&" + roomName.value;
  data.sendName = roomName.value;
  MessageList.value.length = 0;
  roomocket.sendFn("checkedUser", data, (socket) => {
    socket.on("rowMsgList", (data) => {
      MessageList.value = [...data];
    });
  });
};
// 发送消息
const sendMsg = () => {
  let params = {};
  params.content = message.value;
  params.myName = roomName.value;
  params.toName = activeIndex.value;
  params.time = new Date().getTime();
  MessageList.value.push(params);
  //发送消息
  roomocket.sendFn("chatSend", params, (socket) => {
    socket.on("chatRes", (data) => {
      console.log(`接收chatRes消息`, data);
    });
  });
  message.value = ""; //消息输入框制空
};
const enterdown = (e) => {
  if (e.keyCode == 13) {
    sendMsg();
  }
};
</script>
<style lang="scss" scoped>
.talk::-webkit-scrollbar {
  width: 5px; //修改滚动条宽度
}

.el-menu-item:hover {
  background-color: #c4c5c8 !important;
}

.box {
  margin: 20px auto;
  width: 80%;
  height: 600px;
  overflow: hidden;

  .list {
    height: 100%;
    width: 100%;
    // background-color: #ccc;
    background-color: #e6e6e6;

    .headList {
      height: 50px;
      width: 100%;
      background-color: #f7f7f7;
      text-align: center;
      color: black;
      line-height: 50px;
    }

    .text_color {
      // color: white;
      font-size: 16px;

      &:before {
        content: "";
        position: absolute;
        height: 8px;
        width: 8px;
        border-radius: 50%;
        top: 50%;
        left: 5px;
        transform: translateY(-50%);
        background: #33eb42;
      }
    }

    .text_color_is {
      // color: white;
      font-size: 16px;

      &:before {
        content: "";
        position: absolute;
        height: 8px;
        width: 8px;
        border-radius: 50%;
        top: 50%;
        left: 5px;
        transform: translateY(-50%);
        background: #e90a15;
      }
    }
  }

  .title {
    border: 1px solid #ccc;
    font-size: 20px;
    font-weight: 700;
    height: 50px;
    padding-left: 20px;
    line-height: 50px;
    border-bottom: 1px solid #ccc;
    box-sizing: border-box;
  }

  .talk {
    padding: 10px;
    height: 450px;
    width: 100%;
    background-color: #fff;
    border: 1px solid #ccc;
    box-sizing: border-box;
    overflow-y: auto;

    .main_body {
      background-color: #fff;
      padding: 5px;
      box-sizing: border-box;

      .other_user {
        width: 100%;
        height: 60px;
        margin-bottom: 20px;

        .head_img {
          width: 60px;
          height: 60px;
          text-align: center;
          line-height: 60px;
          float: left;
          background-color: rgb(86, 149, 231, 0.3);
          background: url("./img/avatar.png");
          background-size: 100% 100% !important;
        }

        .content {
          margin-left: 50px;
          float: left;
          max-width: 261px;
          background-color: #f1f3f4;
          border-radius: 5px;
          margin: 10px 10px;
          font-size: 13px;
          padding: 10px;
          position: relative;
          word-break: break-word;

          &::before {
            content: "";
            width: 0;
            height: 0;
            border: 5px solid;
            position: absolute;
            left: -10px;
            border-color: transparent #f1f3f4 transparent transparent;
          }
        }
      }

      .my {
        width: 100%;
        height: 100%;
        margin-bottom: 20px;
        overflow: hidden;

        .my_head_img {
          width: 60px;
          height: 60px;
          text-align: center;
          line-height: 60px;
          float: right;
          background-color: rgba(214, 228, 15, 0.3);
          background: url("./img/open-source.jpg");
          background-size: 100% 100% !important;
        }

        .my_content {
          margin-right: 50px;
          float: right;
          max-width: 261px;
          background-color: #9eea6a;
          border-radius: 5px;
          margin: 10px 10px;
          font-size: 13px;
          padding: 10px;
          position: relative;
          word-break: break-word;

          &::before {
            content: "";
            width: 0;
            height: 0;
            border: 5px solid;
            position: absolute;
            right: -10px;
            transform: rotate(180deg);
            border-color: transparent #9eea6a transparent transparent;
          }
        }
      }
    }
  }

  .sendMsg {
    width: 100%;
    height: 100px;
    border: none;
    outline: none;
    text-align: right;
    padding: 5px 5px 20px 5px;
    background-color: white;
    border: 1px solid #ccc;
    box-sizing: border-box;

    textarea {
      width: 100%;
      border: none;
      outline: none;
      resize: none;
    }
  }
}
</style>
